#define NOMINMAX
#include "Windows.h"
#include "NxPhysics.h"
#include "NxControllerManager.h"
#include "Engine.h"
#include "Material.h"
#include "Global.h"
#include "PhysicsScene.h"
#include "PhysXWrappers.h"

namespace FinalRendering
{
	namespace Engine
	{
		using namespace Physics;

		PhysXInitializationFailedException::PhysXInitializationFailedException()
			: Exception(L"Cannot load PhysX library. Please install PhysX first.")
		{
		}

		bool InitEngine()
		{
			MaterialFile::Init();
			CreateGlobal(false);
			return OpenGL::Init();
		}

		void FinalizeEngine()
		{
			MaterialFile::Finalize();
			Program::Finalize();
			DestroyGlobal();
		}

		Engine::Engine()
		{
			static UserAllocator allocator;
			phys = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION);
			ctrlManager=0;
			/*if (!phys)
				throw PhysXInitializationFailedException();
			phys->getFoundationSDK().getRemoteDebugger()->connect ("localhost", 5425);
			
			ctrlManager = NxCreateControllerManager(&allocator);*/
		}

		Engine::~Engine()
		{
			if (phys)
			{
				if (ctrlManager)
					NxReleaseControllerManager(ctrlManager);
				phys->release();
			}
		}

		NxPhysicsSDK * Engine::GetPhysics()
		{
			return phys;
		}

		NxControllerManager * Engine::GetControllerManager()
		{
			return ctrlManager;
		}

		PhysScene * Engine::CreatePhysScene()
		{
			PhysScene * rs = new PhysScene(this);
			return rs;
		}

	}
}